Popular Searches
Popular Course Categories
Popular Courses

Java/Python Coding Questions

Java/Python Coding Questions

Job Preparation

Java/Python Coding Questions for Selenium Automation

Java/Python Coding Questions are an important part of Selenium automation testing interviews because automation engineers are expected to write, understand, debug, and maintain programming logic in addition to knowing Selenium commands. Common coding areas include strings, arrays, collections, numbers, OOP concepts, exception handling, file handling, loops, functions, data structures, and Selenium-specific automation problems.

For Selenium automation roles, coding questions commonly combine programming fundamentals with practical automation tasks such as locating elements, handling dynamic elements, writing reusable methods, working with collections of WebElements, creating Page Object Model classes, implementing waits, taking screenshots, handling windows and frames, and designing reusable framework utilities. Current Selenium interview-preparation resources also commonly cover Java/Python programming, Selenium, TestNG/pytest, POM, data-driven testing, and framework design. :contentReference[oaicite:0]{index=0}

Course Resource: Selenium Training | Register for Selenium Course Demo


1. Why Coding Questions Are Important in Selenium Interviews?

Selenium automation requires programming because test scripts are software programs. A tester may need to create reusable methods, process test data, apply conditions, handle exceptions, work with collections, and implement framework utilities.

  • Tests programming fundamentals.
  • Checks logical problem-solving ability.
  • Tests knowledge of Java or Python syntax.
  • Helps evaluate OOP understanding.
  • Checks array and string manipulation skills.
  • Tests collection handling.
  • Tests exception-handling knowledge.
  • Checks ability to write reusable automation code.
  • Evaluates Selenium-specific coding skills.
  • Tests framework-design fundamentals.


2. Common Coding Question Categories

CategoryCommon Topics
StringsReverse, palindrome, anagram, duplicate characters
ArraysSorting, duplicates, missing numbers, second largest
NumbersPrime, factorial, Fibonacci, Armstrong numbers
CollectionsList, Set, Map, HashMap, ArrayList
OOPInheritance, polymorphism, abstraction, interfaces
Exceptionstry-catch, finally, custom exceptions
SeleniumLocators, waits, windows, frames, alerts, WebElements
FrameworkPOM, DataProvider, utilities, DriverFactory
PythonLists, dictionaries, functions, comprehensions, exceptions


3. Java Coding Question: Reverse a String

One of the most common beginner coding problems is reversing a string.

public class ReverseString {

    public static void main(String[] args) {

        String input = "Selenium";

        String reversed = "";

 

        for (int i = input.length() - 1; i >= 0; i--) {

            reversed += input.charAt(i);

        }

 

        System.out.println(reversed);

    }

}

Output: muineleS

The logic starts from the last character and moves toward the first character.


4. Java Coding Question: Reverse a String Using StringBuilder

public class ReverseString {

    public static void main(String[] args) {

        String input = "Automation";

 

        String result = new StringBuilder(input)

                .reverse()

                .toString();

 

        System.out.println(result);

    }

}

This approach is shorter and commonly used when built-in functionality is allowed.


5. Java Coding Question: Check Palindrome String

A palindrome reads the same from left to right and right to left.

public class Palindrome {

    public static void main(String[] args) {

        String input = "madam";

        String reversed = new StringBuilder(input)

                .reverse()

                .toString();

 

        if (input.equals(reversed)) {

            System.out.println("Palindrome");

        } else {

            System.out.println("Not Palindrome");

        }

    }

}


6. Java Coding Question: Check Palindrome Number

public class NumberPalindrome {

    public static void main(String[] args) {

        int number = 121;

        int original = number;

        int reverse = 0;

 

        while (number != 0) {

            int digit = number % 10;

            reverse = reverse * 10 + digit;

            number = number / 10;

        }

 

        if (original == reverse) {

            System.out.println("Palindrome");

        } else {

            System.out.println("Not Palindrome");

        }

    }

}


7. Java Coding Question: Count Characters in a String

import java.util.HashMap;

import java.util.Map;

 

public class CharacterCount {

    public static void main(String[] args) {

        String input = "selenium";

 

        Map<Character, Integer> count = new HashMap<>();

 

        for (char ch : input.toCharArray()) {

            count.put(ch, count.getOrDefault(ch, 0) + 1);

        }

 

        System.out.println(count);

    }

}

This type of problem tests HashMap usage and character processing.


8. Java Coding Question: Find Duplicate Characters

import java.util.HashMap;

import java.util.Map;

 

public class DuplicateCharacters {

    public static void main(String[] args) {

        String input = "automation";

 

        Map<Character, Integer> map = new HashMap<>();

 

        for (char ch : input.toCharArray()) {

            map.put(ch, map.getOrDefault(ch, 0) + 1);

        }

 

        for (Map.Entry<Character, Integer> entry : map.entrySet()) {

            if (entry.getValue() > 1) {

                System.out.println(entry.getKey());

            }

        }

    }

}


9. Java Coding Question: First Non-Repeating Character

import java.util.LinkedHashMap;

import java.util.Map;

 

public class FirstNonRepeating {

    public static void main(String[] args) {

        String input = "swiss";

 

        Map<Character, Integer> map = new LinkedHashMap<>();

 

        for (char ch : input.toCharArray()) {

            map.put(ch, map.getOrDefault(ch, 0) + 1);

        }

 

        for (Map.Entry<Character, Integer> entry : map.entrySet()) {

            if (entry.getValue() == 1) {

                System.out.println(entry.getKey());

                break;

            }

        }

    }

}


10. Java Coding Question: Check Anagram

Two strings are anagrams when they contain the same characters with the same frequencies, regardless of order.

import java.util.Arrays;

 

public class Anagram {

    public static void main(String[] args) {

        String first = "listen";

        String second = "silent";

 

        char[] a = first.toCharArray();

        char[] b = second.toCharArray();

 

        Arrays.sort(a);

        Arrays.sort(b);

 

        if (Arrays.equals(a, b)) {

            System.out.println("Anagram");

        } else {

            System.out.println("Not Anagram");

        }

    }

}


11. Java Coding Question: Remove Duplicate Characters

import java.util.LinkedHashSet;

import java.util.Set;

 

public class RemoveDuplicates {

    public static void main(String[] args) {

        String input = "selenium";

 

        Set<Character> set = new LinkedHashSet<>();

 

        for (char ch : input.toCharArray()) {

            set.add(ch);

        }

 

        StringBuilder result = new StringBuilder();

 

        for (char ch : set) {

            result.append(ch);

        }

 

        System.out.println(result);

    }

}


12. Java Coding Question: Reverse Words in a Sentence

public class ReverseWords {

    public static void main(String[] args) {

        String input = "Selenium automation testing";

 

        String[] words = input.split(" ");

 

        for (int i = words.length - 1; i >= 0; i--) {

            System.out.print(words[i] + " ");

        }

    }

}

Output: testing automation Selenium


13. Java Coding Question: Count Words in a Sentence

public class WordCount {

    public static void main(String[] args) {

        String input = "Selenium automation testing";

 

        String[] words = input.trim().split("\\s+");

 

        System.out.println("Word count: " + words.length);

    }

}


14. Java Coding Question: Remove Special Characters

public class RemoveSpecialCharacters {

    public static void main(String[] args) {

        String input = "Selenium@123#Test!";

 

        String result = input.replaceAll("[^a-zA-Z0-9]", "");

 

        System.out.println(result);

    }

}

Output: Selenium123Test


15. Java Coding Question: Check Whether String Contains Only Digits

public class DigitCheck {

    public static void main(String[] args) {

        String input = "123456";

 

        if (input.matches("\\d+")) {

            System.out.println("Only digits");

        } else {

            System.out.println("Contains non-digit characters");

        }

    }

}


16. Java Coding Question: Fibonacci Series

public class Fibonacci {

    public static void main(String[] args) {

        int n = 10;

        int first = 0;

        int second = 1;

 

        for (int i = 0; i < n; i++) {

            System.out.print(first + " ");

 

            int next = first + second;

            first = second;

            second = next;

        }

    }

}


17. Java Coding Question: Factorial

public class Factorial {

    public static void main(String[] args) {

        int number = 5;

        int factorial = 1;

 

        for (int i = 1; i <= number; i++) {

            factorial *= i;

        }

 

        System.out.println(factorial);

    }

}


18. Java Coding Question: Check Prime Number

public class PrimeNumber {

    public static void main(String[] args) {

        int number = 29;

        boolean prime = number > 1;

 

        for (int i = 2; i * i <= number && prime; i++) {

            if (number % i == 0) {

                prime = false;

            }

        }

 

        System.out.println(prime ? "Prime" : "Not Prime");

    }

}


19. Java Coding Question: Find Largest Number in an Array

public class LargestNumber {

    public static void main(String[] args) {

        int[] numbers = {10, 25, 5, 40, 15};

 

        int largest = numbers[0];

 

        for (int number : numbers) {

            if (number > largest) {

                largest = number;

            }

        }

 

        System.out.println("Largest: " + largest);

    }

}


20. Java Coding Question: Find Second Largest Number

public class SecondLargest {

    public static void main(String[] args) {

        int[] numbers = {10, 25, 5, 40, 15};

 

        int largest = Integer.MIN_VALUE;

        int second = Integer.MIN_VALUE;

 

        for (int number : numbers) {

            if (number > largest) {

                second = largest;

                largest = number;

            } else if (number > second && number != largest) {

                second = number;

            }

        }

 

        System.out.println("Second largest: " + second);

    }

}


21. Java Coding Question: Find Missing Number in an Array

public class MissingNumber {

    public static void main(String[] args) {

        int[] numbers = {1, 2, 3, 5};

        int n = 5;

 

        int expected = n * (n + 1) / 2;

        int actual = 0;

 

        for (int number : numbers) {

            actual += number;

        }

 

        System.out.println("Missing: " + (expected - actual));

    }

}


22. Java Coding Question: Move Zeros to the End

public class MoveZeros {

    public static void main(String[] args) {

        int[] numbers = {0, 1, 0, 3, 12};

 

        int index = 0;

 

        for (int number : numbers) {

            if (number != 0) {

                numbers[index++] = number;

            }

        }

 

        while (index < numbers.length) {

            numbers[index++] = 0;

        }

 

        for (int number : numbers) {

            System.out.print(number + " ");

        }

    }

}


23. Java Coding Question: Remove Duplicate Numbers from an Array

import java.util.LinkedHashSet;

import java.util.Set;

 

public class DuplicateNumbers {

    public static void main(String[] args) {

        int[] numbers = {1, 2, 2, 3, 4, 4, 5};

 

        Set<Integer> unique = new LinkedHashSet<>();

 

        for (int number : numbers) {

            unique.add(number);

        }

 

        System.out.println(unique);

    }

}


24. Java Coding Question: Sort an Array Without Arrays.sort()

public class SortArray {

    public static void main(String[] args) {

        int[] numbers = {5, 2, 8, 1, 3};

 

        for (int i = 0; i < numbers.length - 1; i++) {

            for (int j = 0; j < numbers.length - 1 - i; j++) {

                if (numbers[j] > numbers[j + 1]) {

                    int temp = numbers[j];

                    numbers[j] = numbers[j + 1];

                    numbers[j + 1] = temp;

                }

            }

        }

 

        for (int number : numbers) {

            System.out.print(number + " ");

        }

    }

}


25. Java Coding Question: Find Duplicate Elements Using Streams

import java.util.Arrays;

import java.util.Map;

import java.util.function.Function;

import java.util.stream.Collectors;

 

public class DuplicateUsingStreams {

    public static void main(String[] args) {

        Integer[] numbers = {1, 2, 2, 3, 3, 4};

 

        Map<Integer, Long> count =

            Arrays.stream(numbers)

                .collect(Collectors.groupingBy(

                    Function.identity(),

                    Collectors.counting()

                ));

 

        count.entrySet()

             .stream()

             .filter(entry -> entry.getValue() > 1)

             .forEach(System.out::println);

    }

}


26. Java Coding Question: ArrayList Operations

import java.util.ArrayList;

import java.util.List;

 

public class ArrayListExample {

    public static void main(String[] args) {

        List<String> browsers = new ArrayList<>();

 

        browsers.add("Chrome");

        browsers.add("Firefox");

        browsers.add("Edge");

 

        System.out.println("Size: " + browsers.size());

 

        for (String browser : browsers) {

            System.out.println(browser);

        }

    }

}

Collection handling is particularly useful in Selenium because methods such as findElements() return multiple WebElements.


27. Selenium Coding Question: Find All Links

List<WebElement> links =

        driver.findElements(By.tagName("a"));

 

for (WebElement link : links) {

    System.out.println(

        link.getText() + " : " +

        link.getAttribute("href")

    );

}

This is a common practical Selenium coding problem because it combines WebElement collections with iteration.


28. Selenium Coding Question: Count Number of Links

List<WebElement> links =

        driver.findElements(By.tagName("a"));

 

System.out.println("Total links: " + links.size());


29. Selenium Coding Question: Find Broken Links

A common interview exercise is to collect all links and verify their HTTP response status. The exact implementation can use Java's HTTP client or another HTTP library rather than navigating every link with Selenium.

List<WebElement> links =

        driver.findElements(By.tagName("a"));

 

for (WebElement link : links) {

    String url = link.getAttribute("href");

 

    if (url != null && !url.isBlank()) {

        System.out.println("Checking: " + url);

    }

}

In a complete implementation, the URL can then be sent through an HTTP client and its response status evaluated.


30. Selenium Coding Question: Get Text of All Buttons

List<WebElement> buttons =

        driver.findElements(By.tagName("button"));

 

for (WebElement button : buttons) {

    System.out.println(button.getText());

}


31. Selenium Coding Question: Find an Element Dynamically

Dynamic elements often require flexible locators instead of relying on unstable attributes.

WebElement element = driver.findElement(

    By.xpath("//button[contains(normalize-space(), 'Login')]")

);

 

element.click();

Dynamic XPath and CSS strategies are commonly discussed in Selenium coding interviews. :contentReference[oaicite:1]{index=1}


32. Selenium Coding Question: Handle Dynamic XPath

String username = "John";

 

WebElement user = driver.findElement(

    By.xpath("//td[normalize-space()='" + username + "']")

);

 

System.out.println(user.getText());

The locator is constructed from a runtime value instead of relying only on a fixed attribute.


33. Selenium Coding Question: Explicit Wait

WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement loginButton = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.id("loginButton")

    )

);

 

loginButton.click();

Explicit waits are useful when a specific condition must be satisfied before an interaction occurs.


34. Selenium Coding Question: Wait for Visibility

WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement message = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("successMessage")

    )

);

 

System.out.println(message.getText());


35. Selenium Coding Question: Handle StaleElementReferenceException

try {

    driver.findElement(By.id("username")).click();

} catch (StaleElementReferenceException e) {

    driver.findElement(By.id("username")).click();

}

A stronger framework approach is to re-locate the element after the DOM has changed rather than repeatedly storing stale element references.


36. Selenium Coding Question: Switch to an Alert

Alert alert = driver.switchTo().alert();

 

System.out.println(alert.getText());

 

alert.accept();


37. Selenium Coding Question: Switch Between Windows

String parentWindow = driver.getWindowHandle();

 

Set<String> windows = driver.getWindowHandles();

 

for (String window : windows) {

    if (!window.equals(parentWindow)) {

        driver.switchTo().window(window);

        break;

    }

}


38. Selenium Coding Question: Handle an IFrame

WebElement frame =

    driver.findElement(By.id("paymentFrame"));

 

driver.switchTo().frame(frame);

 

driver.findElement(By.id("cardNumber"))

      .sendKeys("4111111111111111");

 

driver.switchTo().defaultContent();


39. Selenium Coding Question: Select a Dropdown

Select country = new Select(

    driver.findElement(By.id("country"))

);

 

country.selectByVisibleText("India");


40. Selenium Coding Question: Take a Screenshot

File source = ((TakesScreenshot) driver)

        .getScreenshotAs(OutputType.FILE);

 

File destination =

        new File("screenshots/homepage.png");

 

Files.copy(

    source.toPath(),

    destination.toPath(),

    StandardCopyOption.REPLACE_EXISTING

);

Screenshots are commonly used in automation frameworks for failure diagnosis and reporting.


41. Selenium Coding Question: Scroll Using JavaScript

JavascriptExecutor js =

        (JavascriptExecutor) driver;

 

js.executeScript(

    "window.scrollBy(0,500)"

);


42. Selenium Coding Question: Scroll to an Element

WebElement element =

    driver.findElement(By.id("footer"));

 

JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

js.executeScript(

    "arguments[0].scrollIntoView(true);",

    element

);


43. Selenium Coding Question: Highlight an Element

WebElement element =

    driver.findElement(By.id("username"));

 

JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

js.executeScript(

    "arguments[0].style.border='3px solid red';",

    element

);


44. Selenium Coding Question: Get Attribute Value

WebElement username =

    driver.findElement(By.id("username"));

 

String value =

    username.getAttribute("value");

 

System.out.println(value);

For input fields, getAttribute("value") is commonly used to retrieve the current value entered in the field.


45. Selenium Coding Question: Verify Element Is Displayed

WebElement logo =

    driver.findElement(By.id("logo"));

 

if (logo.isDisplayed()) {

    System.out.println("Logo is displayed");

}


46. Selenium Coding Question: Verify Element Is Enabled

WebElement button =

    driver.findElement(By.id("submit"));

 

if (button.isEnabled()) {

    System.out.println("Button is enabled");

}


47. Selenium Coding Question: Verify Checkbox

WebElement checkbox =

    driver.findElement(By.id("terms"));

 

if (!checkbox.isSelected()) {

    checkbox.click();

}


48. Selenium Coding Question: Reusable Login Method

public void login(

        WebDriver driver,

        String username,

        String password) {

 

    driver.findElement(By.id("username"))

          .sendKeys(username);

 

    driver.findElement(By.id("password"))

          .sendKeys(password);

 

    driver.findElement(By.id("loginButton"))

          .click();

}

Reusable methods are an important part of maintainable automation frameworks.


49. Java OOP Coding Question: Method Overloading

public class LoginHelper {

 

    public void login(String username) {

        System.out.println("Login with username");

    }

 

    public void login(

            String username,

            String password) {

 

        System.out.println(

            "Login with username and password"

        );

    }

}

Method overloading means using the same method name with different parameter lists.


50. Java OOP Coding Question: Method Overriding

class Browser {

    public void open() {

        System.out.println("Opening browser");

    }

}

 

class ChromeBrowser extends Browser {

    @Override

    public void open() {

        System.out.println("Opening Chrome");

    }

}

Method overriding occurs when a subclass provides its own implementation of an inherited method.


51. Java OOP Coding Question: Interface

interface BrowserActions {

    void open();

    void close();

}

 

class ChromeActions implements BrowserActions {

 

    public void open() {

        System.out.println("Chrome opened");

    }

 

    public void close() {

        System.out.println("Chrome closed");

    }

}

Interfaces are useful for defining contracts that can be implemented by different classes.


52. Java Coding Question: Custom Exception

class InvalidUserException extends Exception {

 

    public InvalidUserException(String message) {

        super(message);

    }

}

 

public class LoginValidation {

 

    public static void validate(String username)

            throws InvalidUserException {

 

        if (username == null || username.isBlank()) {

            throw new InvalidUserException(

                "Username cannot be empty"

            );

        }

    }

}


53. Java Coding Question: Try-Catch-Finally

public class ExceptionExample {

    public static void main(String[] args) {

 

        try {

            int result = 10 / 0;

            System.out.println(result);

 

        } catch (ArithmeticException e) {

            System.out.println(

                "Arithmetic error: " + e.getMessage()

            );

 

        } finally {

            System.out.println("Execution completed");

        }

    }

}


54. Python Coding Question: Reverse a String

text = "Selenium"

 

reversed_text = text[::-1]

 

print(reversed_text)

Python slicing provides a concise way to reverse a string.


55. Python Coding Question: Palindrome

text = "madam"

 

if text == text[::-1]:

    print("Palindrome")

else:

    print("Not Palindrome")


56. Python Coding Question: Count Characters

text = "selenium"

 

count = {}

 

for char in text:

    count[char] = count.get(char, 0) + 1

 

print(count)


57. Python Coding Question: Find Duplicate Values

numbers = [1, 2, 2, 3, 4, 4, 5]

 

duplicates = []

 

for number in numbers:

    if numbers.count(number) > 1 and number not in duplicates:

        duplicates.append(number)

 

print(duplicates)


58. Python Coding Question: Find Largest Number

numbers = [10, 25, 5, 40, 15]

 

largest = numbers[0]

 

for number in numbers:

    if number > largest:

        largest = number

 

print(largest)


59. Python Coding Question: Remove Duplicates

numbers = [1, 2, 2, 3, 4, 4, 5]

 

unique_numbers = list(dict.fromkeys(numbers))

 

print(unique_numbers)


60. Python Coding Question: Fibonacci Series

n = 10

first = 0

second = 1

 

for _ in range(n):

    print(first, end=" ")

 

    first, second = second, first + second


61. Python Coding Question: Prime Number

number = 29

 

if number < 2:

    print("Not Prime")

else:

    is_prime = True

 

    for i in range(2, int(number ** 0.5) + 1):

        if number % i == 0:

            is_prime = False

            break

 

    print("Prime" if is_prime else "Not Prime")


62. Python Selenium: Open Browser

from selenium import webdriver

 

driver = webdriver.Chrome()

 

driver.get("https://example.com")

 

print(driver.title)

 

driver.quit()

Selenium's Python bindings provide a similar browser-automation model to Java, although the language syntax and test framework integration differ. :contentReference[oaicite:2]{index=2}


63. Python Selenium: Find an Element

from selenium.webdriver.common.by import By

 

username = driver.find_element(

    By.ID,

    "username"

)

 

username.send_keys("testuser")


64. Python Selenium: Explicit Wait

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

from selenium.webdriver.common.by import By

 

wait = WebDriverWait(driver, 10)

 

button = wait.until(

    EC.element_to_be_clickable(

        (By.ID, "loginButton")

    )

)

 

button.click()


65. Python Selenium: Find Multiple Elements

from selenium.webdriver.common.by import By

 

links = driver.find_elements(

    By.TAG_NAME,

    "a"

)

 

for link in links:

    print(link.text, link.get_attribute("href"))


66. Python Selenium: Take Screenshot

driver.save_screenshot(

    "screenshots/homepage.png"

)


67. Python Selenium: Handle Alert

alert = driver.switch_to.alert

 

print(alert.text)

 

alert.accept()


68. Python Selenium: Handle IFrame

frame = driver.find_element(

    By.ID,

    "paymentFrame"

)

 

driver.switch_to.frame(frame)

 

driver.find_element(

    By.ID,

    "cardNumber"

).send_keys("4111111111111111")

 

driver.switch_to.default_content()


69. Python Selenium: Handle Multiple Windows

parent = driver.current_window_handle

 

for window in driver.window_handles:

    if window != parent:

        driver.switch_to.window(window)

        break


70. Python Selenium: Reusable Login Function

from selenium.webdriver.common.by import By

 

def login(driver, username, password):

    driver.find_element(

        By.ID, "username"

    ).send_keys(username)

 

    driver.find_element(

        By.ID, "password"

    ).send_keys(password)

 

    driver.find_element(

        By.ID, "loginButton"

    ).click()


71. Selenium Coding: Page Object Model

The Page Object Model separates page-specific Selenium interactions from test logic. This makes test code easier to maintain when page locators or workflows change.

public class LoginPage {

 

    private WebDriver driver;

 

    private By username =

        By.id("username");

 

    private By password =

        By.id("password");

 

    private By loginButton =

        By.id("loginButton");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void login(

            String user,

            String pass) {

 

        driver.findElement(username)

              .sendKeys(user);

 

        driver.findElement(password)

              .sendKeys(pass);

 

        driver.findElement(loginButton)

              .click();

    }

}

POM is a common framework-design topic in Selenium interviews. :contentReference[oaicite:3]{index=3}


72. TestNG Coding Question: DataProvider

TestNG DataProvider is commonly used to execute the same test method with multiple data sets.

@DataProvider(name = "loginData")

public Object[][] loginData() {

    return new Object[][] {

        {"admin", "admin123"},

        {"manager", "manager123"},

        {"employee", "employee123"}

    };

}

 

@Test(dataProvider = "loginData")

public void loginTest(

        String username,

        String password) {

 

    System.out.println(username);

}

DataProvider is specifically designed for data-driven test execution and is frequently used in Selenium/TestNG frameworks. :contentReference[oaicite:4]{index=4}


73. TestNG Coding Question: Assertion

Assert.assertEquals(

    driver.getTitle(),

    "Dashboard"

);

 

Assert.assertTrue(

    driver.getCurrentUrl().contains("dashboard")

);


74. TestNG Coding Question: Retry Failed Tests

public class RetryAnalyzer

        implements IRetryAnalyzer {

 

    private int count = 0;

    private int maxRetry = 2;

 

    @Override

    public boolean retry(ITestResult result) {

 

        if (count < maxRetry) {

            count++;

            return true;

        }

 

        return false;

    }

}

A retry mechanism should be used carefully. Automatically retrying every failure can hide genuine defects or synchronization problems.


75. Coding Question: Driver Factory

A Driver Factory centralizes browser creation and helps avoid duplicating WebDriver initialization code throughout the framework.

public class DriverFactory {

 

    public static WebDriver createDriver(

            String browser) {

 

        if (browser.equalsIgnoreCase("chrome")) {

            return new ChromeDriver();

        }

 

        if (browser.equalsIgnoreCase("firefox")) {

            return new FirefoxDriver();

        }

 

        if (browser.equalsIgnoreCase("edge")) {

            return new EdgeDriver();

        }

 

        throw new IllegalArgumentException(

            "Unsupported browser: " + browser

        );

    }

}


76. Coding Question: Read Configuration Properties

Properties properties = new Properties();

 

try (FileInputStream input =

        new FileInputStream("config.properties")) {

 

    properties.load(input);

 

    String url =

        properties.getProperty("url");

 

    System.out.println(url);

}


77. Coding Question: Read a File in Java

Path path = Paths.get("testdata.txt");

 

List<String> lines =

    Files.readAllLines(path);

 

for (String line : lines) {

    System.out.println(line);

}


78. Coding Question: HashMap Iteration

Map<String, String> users =

    new HashMap<>();

 

users.put("admin", "Admin");

users.put("manager", "Manager");

 

for (Map.Entry<String, String> entry :

        users.entrySet()) {

 

    System.out.println(

        entry.getKey() + " : " +

        entry.getValue()

    );

}


79. Coding Question: Java Stream Filter

List<Integer> numbers =

    Arrays.asList(10, 15, 20, 25, 30);

 

List<Integer> evenNumbers =

    numbers.stream()

           .filter(number -> number % 2 == 0)

           .collect(Collectors.toList());

 

System.out.println(evenNumbers);


80. Coding Question: Java Stream Map

List<String> names =

    Arrays.asList("john", "david", "robert");

 

List<String> upperCase =

    names.stream()

         .map(String::toUpperCase)

         .collect(Collectors.toList());

 

System.out.println(upperCase);


81. Coding Question: Find Maximum Using Streams

List<Integer> numbers =

    Arrays.asList(10, 25, 5, 40, 15);

 

int maximum =

    numbers.stream()

           .max(Integer::compareTo)

           .orElseThrow();

 

System.out.println(maximum);


82. Coding Question: Find Second Highest Using Streams

List<Integer> numbers =

    Arrays.asList(10, 25, 5, 40, 15);

 

int secondHighest =

    numbers.stream()

           .distinct()

           .sorted(Comparator.reverseOrder())

           .skip(1)

           .findFirst()

           .orElseThrow();

 

System.out.println(secondHighest);


83. Selenium Coding Question: Login Automation

WebDriver driver = new ChromeDriver();

 

driver.get("https://example.com/login");

 

driver.findElement(By.id("username"))

      .sendKeys("testuser");

 

driver.findElement(By.id("password"))

      .sendKeys("password");

 

driver.findElement(By.id("loginButton"))

      .click();

 

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

wait.until(

    ExpectedConditions.urlContains("dashboard")

);

 

driver.quit();


84. Selenium Coding Question: Search Automation

WebElement searchBox =

    driver.findElement(By.id("search"));

 

searchBox.clear();

searchBox.sendKeys("Laptop");

 

driver.findElement(

    By.id("searchButton")

).click();


85. Selenium Coding Question: Extract Table Data

List<WebElement> rows =

    driver.findElements(

        By.cssSelector("table tbody tr")

    );

 

for (WebElement row : rows) {

    System.out.println(row.getText());

}

For a specific cell, the row can be further searched for its child cells.


86. Selenium Coding Question: Find a Row Containing Text

WebElement row = driver.findElement(

    By.xpath(

        "//table//tr[td[normalize-space()='John']]"

    )

);

 

System.out.println(row.getText());


87. Selenium Coding Question: Dynamic Web Table

List<WebElement> rows =

    driver.findElements(

        By.cssSelector("table tbody tr")

    );

 

for (WebElement row : rows) {

 

    List<WebElement> cells =

        row.findElements(By.tagName("td"));

 

    for (WebElement cell : cells) {

        System.out.print(

            cell.getText() + " | "

        );

    }

 

    System.out.println();

}


88. Selenium Coding Question: Find a Specific Table Cell

String username = "John";

 

WebElement email = driver.findElement(

    By.xpath(

        "//tr[td[normalize-space()='" +

        username +

        "']]/td[3]"

    )

);

 

System.out.println(email.getText());


89. Selenium Coding Question: Verify Page Title

String actualTitle = driver.getTitle();

 

if (actualTitle.equals("Dashboard")) {

    System.out.println("Title matched");

} else {

    System.out.println("Title mismatch");

}


90. Selenium Coding Question: Verify URL

String currentUrl =

    driver.getCurrentUrl();

 

if (currentUrl.contains("/dashboard")) {

    System.out.println("Correct page");

}


91. Coding Question: Wait for Page Load

new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

).until(

    webDriver ->

        ((JavascriptExecutor) webDriver)

            .executeScript(

                "return document.readyState"

            )

            .equals("complete")

);


92. Coding Question: Close Current Browser Window

driver.close();

close() closes the current browser window or tab controlled by the driver.


93. Coding Question: Close the Entire Browser Session

driver.quit();

quit() ends the WebDriver session and closes the associated browser windows.


94. Java vs Python Coding Syntax

TaskJavaPython
VariableString name = "John";name = "John"
Conditionif (x > 10)if x > 10:
Loopfor (int x : numbers)for x in numbers:
Functionpublic void login()def login():
ListList<String>list
Dictionary/MapHashMapdict
Exceptiontry/catchtry/except


95. Java vs Python Selenium

FeatureJavaPython
Browser DriverWebDriverWebDriver
Test FrameworkTestNG/JUnitpytest/unittest
Page ObjectsJava classesPython classes
CollectionsList/Set/Maplist/set/dict
AssertionsAssert/JUnit/TestNGassert/pytest
Data DrivenDataProvider/other sourcespytest parametrization/other sources

The Selenium concepts are transferable between Java and Python even though their syntax and surrounding test frameworks differ. :contentReference[oaicite:5]{index=5}


96. Common Selenium Coding Interview Scenarios

  • Write a script to launch Chrome.
  • Write a script to launch Firefox.
  • Find all links on a page.
  • Count all links.
  • Extract text and href from links.
  • Handle a dynamic element.
  • Write an explicit wait.
  • Handle an alert.
  • Handle an iframe.
  • Handle multiple windows.
  • Handle a dropdown.
  • Take a screenshot.
  • Scroll to an element.
  • Highlight an element.
  • Handle a stale element.
  • Read data from a table.
  • Find a specific table row.
  • Build a login method.
  • Create a Page Object.
  • Create a DataProvider.
  • Create a Driver Factory.
  • Implement retry logic.
  • Read configuration data.
  • Design a reusable Selenium framework.

These types of Selenium, Java, POM, TestNG, and framework questions appear frequently in automation interview-preparation material. :contentReference[oaicite:6]{index=6}


97. Common Coding Mistakes in Selenium Interviews

  • Writing code without explaining the approach.
  • Using hard-coded waits such as Thread.sleep() everywhere.
  • Ignoring synchronization problems.
  • Using fragile XPath expressions unnecessarily.
  • Sharing a WebDriver instance unsafely across parallel tests.
  • Not closing the browser after execution.
  • Ignoring exception handling.
  • Writing duplicate Selenium code.
  • Putting all Selenium logic directly inside test methods.
  • Using hard-coded credentials in source code.
  • Not validating expected results.
  • Using global/static state without considering parallel execution.
  • Not separating test data, page logic, and test logic.


98. How to Approach a Coding Question

  1. Understand the requirement: Read the problem carefully.
  2. Clarify the input: Identify the expected input and output.
  3. Explain the approach: Describe the logic before writing code.
  4. Write simple code: Start with a readable solution.
  5. Consider edge cases: Think about empty, null, duplicate, and invalid values.
  6. Test the solution: Use sample inputs.
  7. Discuss complexity: Explain time and space considerations when appropriate.
  8. Improve the solution: Mention alternative approaches if relevant.


99. Coding Interview Preparation Flow

Core Java/Python

       |

       v

Strings & Arrays

       |

       v

Collections

       |

       v

OOP Concepts

       |

       v

Exception Handling

       |

       v

Selenium Coding

       |

       v

TestNG / pytest

       |

       v

Page Object Model

       |

       v

Data-Driven Testing

       |

       v

Framework Utilities

       |

       v

Real-World Automation Scenarios


100. Practical Mini Project

Build a data-driven Selenium login automation framework using Java, TestNG, and Page Object Model.

Project Requirements

  • Create a Driver Factory.
  • Create a Login Page class.
  • Create a Login Test class.
  • Create a DataProvider containing multiple login combinations.
  • Use explicit waits.
  • Validate the expected dashboard or error message.
  • Take screenshots for failed tests.
  • Generate test reports.
  • Store configuration separately.
  • Execute the project using Maven.

Suggested Project Structure

src

|-- main

|   |-- java

|       |-- pages

|       |   |-- LoginPage.java

|       |

|       |-- utilities

|           |-- DriverFactory.java

|           |-- ConfigReader.java

|

|-- test

    |-- java

        |-- tests

        |   |-- LoginTest.java

        |

        |-- data

            |-- LoginDataProvider.java

 

pom.xml

testng.xml


101. Complete Mini Project Flow

TestNG

   |

   v

DataProvider

   |

   v

Login Test

   |

   v

Driver Factory

   |

   v

Chrome / Firefox / Edge

   |

   v

Login Page Object

   |

   v

Selenium WebDriver

   |

   v

Application

   |

   v

Assertions

   |

   v

Screenshot / Report


102. Interview Questions for Java/Python Coding

1. How do you reverse a string?

You can use a loop, StringBuilder in Java, or slicing in Python.

2. How do you find duplicate characters?

A HashMap in Java or a dictionary in Python can be used to count character frequencies.

3. How do you find the second largest number?

You can maintain the largest and second-largest values in one traversal or sort distinct values and select the second value.

4. How do you find duplicate numbers?

You can use a Set, frequency map, or stream-based grouping approach.

5. What is the difference between ArrayList and HashSet?

ArrayList preserves insertion order and permits duplicates, while HashSet is designed for unique elements and does not guarantee insertion order.

6. What is HashMap?

HashMap stores key-value pairs and provides efficient lookup based on keys under normal conditions.

7. What is method overloading?

Method overloading means having methods with the same name but different parameter lists.

8. What is method overriding?

Method overriding occurs when a subclass provides a specific implementation of an inherited method.

9. What is an interface?

An interface defines a contract that implementing classes must fulfill.

10. Why is exception handling important in automation?

Exception handling allows automation code to respond appropriately to expected runtime problems and perform cleanup when necessary.

11. How do you find all links in Selenium?

Use findElements(By.tagName("a")) and iterate over the returned WebElements.

12. How do you handle dynamic elements?

Use stable attributes and flexible CSS or XPath expressions, combined with appropriate synchronization.

13. How do you handle synchronization?

Explicit waits are commonly used to wait for specific conditions such as visibility or clickability.

14. How do you handle multiple browser windows?

Use getWindowHandle() and getWindowHandles(), then switch to the required window.

15. How do you handle frames?

Use driver.switchTo().frame() and return to the main document using defaultContent().

16. What is Page Object Model?

POM is a design pattern that represents application pages as classes and keeps page interaction logic separate from test logic.

17. What is DataProvider?

DataProvider supplies multiple sets of data to a TestNG test method.

18. Why should Selenium code be reusable?

Reusable methods reduce duplication and make framework maintenance easier.

19. What is a Driver Factory?

A Driver Factory centralizes browser-driver creation and configuration.

20. What should you do when a Selenium test fails intermittently?

Investigate synchronization, locator stability, test-data isolation, browser/environment differences, and shared state before considering a retry.


103. Quick Revision Table

TopicKey Point
String ReverseReverse characters using a loop or language utility
PalindromeCompare original and reversed values
AnagramCompare character frequencies/order-independent representations
ArrayPractice sorting, duplicates, missing values, largest values
HashMapUseful for key-value and frequency-count problems
StreamsUseful for filtering, mapping, grouping, and aggregation
OOPInheritance, abstraction, interfaces, polymorphism
ExceptionsHandle runtime problems and cleanup appropriately
WebElementRepresents an element on a web page
findElements()Returns multiple matching elements
Explicit WaitWaits for a specific condition
AlertHandles JavaScript browser alerts
FrameSwitches WebDriver context to an iframe/frame
Window HandleIdentifies browser windows/tabs
POMSeparates page interaction from test logic
DataProviderSupplies multiple test-data combinations
Driver FactoryCentralizes WebDriver creation


104. Learning Roadmap for Java/Python Coding Questions

  1. Learn basic Java or Python syntax.
  2. Practice variables, operators, conditions, and loops.
  3. Practice strings and character manipulation.
  4. Practice arrays and lists.
  5. Learn Set and Map/Dictionary concepts.
  6. Practice sorting and searching problems.
  7. Learn OOP concepts.
  8. Practice exception handling.
  9. Learn file handling.
  10. Practice Java Streams or Python comprehensions.
  11. Learn Selenium WebDriver coding.
  12. Practice locators and dynamic elements.
  13. Practice waits and synchronization.
  14. Practice alerts, frames, windows, and dropdowns.
  15. Practice WebElement collections.
  16. Learn TestNG or pytest.
  17. Learn DataProvider or parameterization.
  18. Learn Page Object Model.
  19. Build reusable framework utilities.
  20. Practice real-world Selenium interview scenarios.


105. Final Summary

Java and Python coding skills are fundamental for Selenium automation because Selenium test scripts are software programs that require programming logic, data handling, reusable methods, object-oriented design, and exception handling.

For Java-based Selenium automation, important preparation areas include strings, arrays, collections, HashMap, Streams, OOP, exceptions, file handling, Selenium WebDriver, TestNG, DataProvider, POM, and framework utilities. Python-based Selenium automation requires similar problem-solving skills using Python syntax, lists, dictionaries, functions, classes, exceptions, and pytest or another suitable test framework.

Selenium-specific coding questions commonly involve locators, dynamic elements, explicit waits, alerts, frames, windows, dropdowns, WebElement collections, screenshots, tables, reusable methods, Page Object Model, and framework components. Current interview-preparation resources similarly emphasize programming fundamentals, Selenium, waits, POM, TestNG/pytest, data-driven testing, and framework design. :contentReference[oaicite:7]{index=7}

Final Takeaway: The strongest preparation combines programming fundamentals with practical automation. Instead of memorizing isolated programs, practice explaining the logic, writing clean reusable code, handling edge cases, and applying the solution to real Selenium automation scenarios.


106. Course Resources

Learn more about Selenium automation and related testing concepts:

whatsapp